package com.asset.dispoal.file.head.service.commom;


import com.asset.dispoal.file.head.domain.db.mapper.UserMapper;
import com.asset.dispoal.file.head.domain.redis.entity.UserRedis;
import com.asset.dispoal.file.head.dto.HeadImgRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;
import tech.mhuang.pacebox.springboot.redis.commands.IRedisExtCommands;

import java.io.File;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @author qr
 * @date 2022/3/16$
 */
@Component
public class SaveHeadCommand implements BaseCommand<HeadImgRequest, Result> {

    @Autowired
    private Environment environment;

    @Autowired
    private BaseIdeable<String> idWorker;

    @Autowired
    private IRedisExtCommands redisExtCommands;


    @Autowired
    UserMapper userMapper;

    @Override
    public Result execute(HeadImgRequest headImgRequest) {
        String headUrl = environment.getProperty("file.evidence.url");
        String property = environment.getProperty("file.head.url");
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int month = now.getMonthValue();
        int day = now.getDayOfMonth();
        //文件路径
        String resolveUrl = "/" +
                year +
                "/" +
                month +
                "/" +
                day;
        property = property + resolveUrl;
        File parentResolveFile = new File(headUrl + "/" + property);
        if (!parentResolveFile.exists()) {
            parentResolveFile.mkdirs();
        }
        String generateId = idWorker.generateId();
        String originalFilename = headImgRequest.getMultipartFile().getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        UserRedis userRedis = null;
        try {
            headImgRequest.getMultipartFile().transferTo(new File(headUrl + "/" + property + "/" + generateId + suffix));
            userMapper.update("/" + property + "/" + generateId + suffix, headImgRequest.getUserId());
            userRedis = modifyUserCache("/" + property + "/" + generateId + suffix);
        } catch (Exception e) {
            throw new BusinessException(Result.SYS_FAILD, "头像更新失败", e);
        }
        return Result.ok(userRedis);
    }


    private UserRedis modifyUserCache(String logoUrl) {
        final String userId = GlobalHeaderThreadLocal.getOrException().getUserId();
        String userIdConfigure = environment.getProperty("user.cache.user_id");
        String userAccountConfigure = environment.getProperty("user.cache.user_account");
        HashMap<String, String> hashMap = redisExtCommands.hget(userIdConfigure, userId, HashMap.class);
        UserRedis redis = userMapper.queryUser(userId);
        redis.setAuthType(hashMap.get("authType"));
        redis.setToken(hashMap.get("token"));
        redis.setLogo(logoUrl);
        redis.setAuthType(redis.getAuthType());
        redisExtCommands.hset(userIdConfigure, userId, redis);
        redisExtCommands.hset(userAccountConfigure, hashMap.get("account"), redis);
        return redis;
    }
}
